<template>
  <div class="particle-setting">
    <div class="header">
      <div class="left">
        <div class="back" @click="back">
          <SvgIcon icon-class="ic_返回" />
          <span>返回</span>
        </div>
      </div>
      <el-button type="primary" @click="saveConfirm"> 保存并退出编辑 </el-button>
    </div>
    <div class="iframe-wrap">
      <iframe ref="iframeRef" src="/cimup/particle/editor.html" frameborder="0"></iframe>
    </div>
  </div>
  <!-- 插入图片 -->
  <ChoosePic
    v-if="choosePicVisible"
    v-model="choosePicVisible"
    @close-handle="choosePicClose"
    @sel-pic="picChange"
  />
  <!-- 插入模型 -->
  <ChooseResource
    v-if="chooseResourceVisible"
    v-model="chooseResourceVisible"
    @close-handle="chooseModelClose"
  />

  <el-dialog
    v-model="dialogVisible"
    title="新增模型"
    :width="500"
    :append-to-body="false"
    custom-class="center-detail"
    @close="addModelClose"
  >
    <el-form ref="addModelRef" :model="addModelForm" label-width="100px">
      <el-form-item
        label="名称"
        prop="effName"
        :rules="[{ required: true, message: '名称不能为空' }]"
      >
        <el-input v-model="addModelForm.effName" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="缩略图" prop="thumbnail">
        <el-upload
          action="#"
          :limit="1"
          accept=".jpg,.png"
          :show-file-list="false"
          :before-upload="handleBeforeUpload"
        >
          <template #default>
            <div v-if="effCover">
              <img :src="retFilePath(effCover)" alt="" class="thumbnail-preview" />
            </div>
            <div v-else class="btn-upload">
              <SvgIcon icon-class="add" />
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addModelClose">取消</el-button>
        <el-button color="#0560FD" type="primary" @click="save">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { commonUpload } from '@/api/common';
import { CommonUploadResp } from '@/api/common/types';
import { createEffect, editEffect } from '@/api/scene';
import ChoosePic from '@/components/choose-pic.vue';
import { ElMessage } from 'element-plus';
import { debounce } from 'lodash';
import { retFilePath } from '@/utils';

defineOptions({
  name: 'ParticleSetting',
});

interface IProps {
  json: string;
  effect: any;
}

const props = withDefaults(defineProps<IProps>(), {
  json: '',
  effect: null,
});

const emits = defineEmits(['closeHandle']);

const iframeRef = ref();
const choosePicVisible = ref<boolean>(false);
const chooseResourceVisible = ref<boolean>(false);
const dialogVisible = ref<boolean>(false);
const addModelRef = ref();
const addModelForm = ref<any>({
  effName: '',
});

const effCover = ref('');

onMounted(() => {
  effCover.value = props.effect ? props.effect.effCover : '';
  window.onmessage = function (e: any) {
    if (e.data.type === 'export') {
      const treeJson = e.data.data;
      if (props.effect && props.effect.effectId) {
        const fData = new FormData();
        fData.set('effId', props.effect.effectId);
        fData.set('effName', props.effect.effectName);
        fData.set('effCover', effCover.value || props.effect.effCover);
        fData.set('configJson', treeJson);
        editEffect({ data: fData }).then(() => {
          emits('closeHandle', treeJson);
        });
      } else {
        const fData = new FormData();
        fData.set('effType', 4);
        fData.set('effName', addModelForm.value.effName);
        fData.set('effDesp', '');
        fData.set('effCover', effCover.value || props.effect.effCover);
        fData.set('quoteUrl', '');
        fData.set('configJson', treeJson);
        createEffect({ data: fData }).then(() => {
          addModelClose();
          emits('closeHandle', treeJson);
        });
      }
      return;
    }
    if (e.data.type === 'loaded') {
      nextTick(() => {
        iframeRef.value &&
          iframeRef.value.contentWindow.postMessage(
            {
              type: 'init',
              data: { json: props.json, NODE_ENV: process.env.NODE_ENV },
            },
            '*'
          );
      });
      return;
    }
    if (e.data.type === 'picChange') {
      choosePicVisible.value = true;
      return;
    }
    if (e.data.type === 'addModel') {
      chooseResourceVisible.value = true;
    }
  };
});

const handleBeforeUpload = async (file: any) => {
  if (!file) {
    return;
  }
  const fileSuffix = file.name.substring(file.name.lastIndexOf('.'));
  if (!['.jpg', '.png'].includes(fileSuffix)) {
    ElMessage.warning('文件格式错误');
    return false;
  }
  if (file.size / 1024 / 1024 / 1024 > 50) {
    ElMessage.warning('文件大小不能超过50G');
    return false;
  }

  const res: CommonUploadResp = await commonUpload(file);
  effCover.value = res.files[0].refAddress!;
  return false;
};

const save = debounce(
  async () => {
    if (!(props.effect && props.effect.effectId)) {
      const validateResult = await addModelRef.value.validate();
      if (!validateResult) return;
    }
    iframeRef.value.contentWindow.postMessage({ type: 'save', data: '' }, '*');
  },
  300,
  {
    leading: true,
    trailing: false,
  }
);

function back() {
  emits('closeHandle');
}

function choosePicClose() {
  choosePicVisible.value = false;
}

function chooseModelClose() {
  chooseResourceVisible.value = false;
}

function picChange(src: string) {
  choosePicClose();
  iframeRef.value.contentWindow.postMessage({ type: 'picSelected', data: src }, '*');
}

function addModelClose() {
  dialogVisible.value = false;
  addModelRef.value.resetFields();
}

function saveConfirm() {
  if (props.effect && props.effect.effectId) {
    save();
  } else {
    dialogVisible.value = true;
  }
}
</script>

<style lang="less" scoped>
.particle-setting {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  z-index: 10;
  display: flex;
  flex-direction: column;
  .header {
    display: flex;
    align-items: center;
    flex-shrink: 0;
    height: 60px;
    background: #1d1e1f;
    border-bottom: 2px solid #000000;
    pointer-events: initial;
    padding: 0 20px 0 0;
    .left {
      display: flex;
      align-items: center;
      width: 30%;
      .back {
        display: flex;
        align-items: center;
        white-space: nowrap;
        margin-right: 24px;
        cursor: pointer;
        .svg-icon {
          margin-left: 12px;
          margin-right: 4px;
          font-size: 20px;
        }
      }
    }
    .el-button {
      margin-left: auto;
    }
  }
  .iframe-wrap {
    flex: 1;
    iframe {
      width: 100%;
      height: 100%;
    }
  }
}

:deep(.btn-upload) {
  width: 32px;
  height: 32px;
  border: 1px solid #ccc;
  border-radius: 4px;
  display: flex;
  .svg-icon {
    margin: auto;
    font-size: 24px;
  }
}
:deep(.thumbnail-preview) {
  width: 100px;
}
</style>
